/**
 * @date: 2025/3/22
 * @author: 小红
 * @Description: 一些组件的 hooks
 */

import { ref } from 'vue';
import { useFileDialog, type UseFileDialogOptions } from '@vueuse/core';

/**
 * 使用 ref 推导 组件类型
 * @param _comp
 */
export function useCompRef<T extends abstract new (...args: any) => any>(_comp: T) {
	return ref<InstanceType<T>>();
}

/**
 * 上传文件
 */
export function useUploadFile(options?: UseFileDialogOptions) {
	options = options || {
		accept: 'image/*',
		multiple: false,
	};

	const { open, reset, onCancel, onChange } = useFileDialog(options);

	const customParam = ref<string>();

	function handleOpen(param: any) {
		customParam.value = param;
		open();
	}

	function handleOnChange(callback: (file: FileList, param: any) => void) {
		onChange((files) => {
			if (files && files.length > 0 && customParam.value) {
				callback(!options?.multiple ? files : files, customParam.value);
				reset();
			}
			customParam.value = undefined;
		});
	}

	return {
		onCancel,
		handleOnChange,
		handleOpen,
	};
}
